<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */

namespace Admin\Model;

use Think\Model;

class MenuModel extends Model {

    protected $_validate = array(
        array('title','require','标题必须填写', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
//        array('url','require','链接必须填写', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('title', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
    );

    public function get($query){
        $map = [];

        $query['id']>0 && $map['id'] = $query['id'];
        isset($query['pid']) && $map['pid'] = $query['pid'];

        $result = $this->where($map)->order('sort asc')->select();
        return $result;
    }

    public function update($data){

        // 无status则默认为1
        $data['status'] != 1 && $data['status'] != 0 && $data['status'] = 1;

        // 程序出口值,0:失败, >1:成功, 以位运算的或运算来修改其值
        $res = 1;

        // 验证数据,验证失败则 res = 0
        $res &= (bool)($data = $this->create($data)) ;

        // 如果id存在,则更新,保存失败则 res = 0
        $res && $data['id'] && ($res &= (bool)$this->save($data));

        // 如果id不存在,则新增,新增成功则 res = id（返回ID）
        $res && !$data['id'] && ($id = $this->add($data)) && ($res = $id);

        // 程序出口
        return $res;
    }



    public function remove($id){
        if ( !$id ) {
            $this->error = '待删除项为空';
            return false;
        }
        $map = [
            'id'=>[
                'IN',
                $id
            ]
        ];
        if ( $this->where($map)->delete() ) {
            S('DB_CONFIG', null);
            return true;
        } else {
            return false;
        }
    }



    /**
     * 获取控制器菜单数组,二级菜单元素位于一级菜单的'_child'元素中
     */
    public function getMenus($controller=CONTROLLER_NAME){
//        $menus  =   session('ADMIN_MENU_LIST.'.$controller);
        if(empty($menus)){
            // 获取主菜单
            $where['pid']   =   0;
            $where['hide']  =   0;
            if(!C('DEVELOP_MODE')){ // 是否开发者模式
                $where['is_dev']    =   0;
            }
            $menus['main']  =   M('Menu')->where($where)->order('sort asc')->field('id,title,url')->select();
//            dump($menus);
            $menus['child'] =   array(); //设置子节点
//            foreach ($menus['main'] as $key => $item) {
//                // 判断主菜单权限
//                if ( !IS_ROOT && !$this->checkRule(strtolower(MODULE_NAME.'/'.$item['url']),AuthRuleModel::RULE_MAIN,null) ) {
//                    unset($menus['main'][$key]);
//                    continue;//继续循环
//                }
//                if(strtolower(CONTROLLER_NAME.'/'.ACTION_NAME)  == strtolower($item['url'])){
//                    $menus['main'][$key]['class']='current';
//                }
//            }

            $where_child['pid']   =   array('gt',0);
            $where_child['hide']  =   0;
            if(!C('DEVELOP_MODE')){ // 是否开发者模式
                $where_child['is_dev']    =   0;
            }
            $menus['child']  =   M('Menu')->where($where_child)->order('sort asc')->field('id,pid,title,url')->select();
            foreach($menus['main'] as $key=>$value){
                foreach( $menus['child'] as $v){
                    if ( $v['pid'] == $value['id'])
                        $menus['main'][$key]['child'][] = $v;
                }
            }
            // 查找当前子菜单
//            $pid = M('Menu')->where("pid !=0 AND url like '%{$controller}/".ACTION_NAME."%'")->getField('pid');
//            if($pid){
//                // 查找当前主菜单
//                $nav =  M('Menu')->find($pid);
//                if($nav['pid']){
//                    $nav    =   M('Menu')->find($nav['pid']);
//                }
//                foreach ($menus['main'] as $key => $item) {
//                    // 获取当前主菜单的子菜单项
//                    if($item['id'] == $nav['id']){
//                        $menus['main'][$key]['class']='current';
//                        //生成child树
//                        $groups = M('Menu')->where(array('group'=>array('neq',''),'pid' =>$item['id']))->distinct(true)->getField("group",true);
//                        //获取二级分类的合法url
//                        $where          =   array();
//                        $where['pid']   =   $item['id'];
//                        $where['hide']  =   0;
//                        if(!C('DEVELOP_MODE')){ // 是否开发者模式
//                            $where['is_dev']    =   0;
//                        }
//                        $second_urls = M('Menu')->where($where)->getField('id,url');
//
//                        if(!IS_ROOT){
//                            // 检测菜单权限
//                            $to_check_urls = array();
//                            foreach ($second_urls as $key=>$to_check_url) {
//                                if( stripos($to_check_url,MODULE_NAME)!==0 ){
//                                    $rule = MODULE_NAME.'/'.$to_check_url;
//                                }else{
//                                    $rule = $to_check_url;
//                                }
//                                if($this->checkRule($rule, AuthRuleModel::RULE_URL,null))
//                                    $to_check_urls[] = $to_check_url;
//                            }
//                        }
//                        // 按照分组生成子菜单树
//                        foreach ($groups as $g) {
//                            $map = array('group'=>$g);
//                            if(isset($to_check_urls)){
//                                if(empty($to_check_urls)){
//                                    // 没有任何权限
//                                    continue;
//                                }else{
//                                    $map['url'] = array('in', $to_check_urls);
//                                }
//                            }
//                            $map['pid']     =   $item['id'];
//                            $map['hide']    =   0;
//                            if(!C('DEVELOP_MODE')){ // 是否开发者模式
//                                $map['is_dev']  =   0;
//                            }
//                            $menuList = M('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort asc')->select();
//                            $menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
//                        }
//                    }
//                }
//            }
//            session('ADMIN_MENU_LIST.'.$controller,$menus);
        }
//        dump($menus);
        return $menus;
    }
}